#!/bin/bash

sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring

curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor |
    sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

gpg --dry-run --quiet --no-keyring --import --import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" |
    sudo tee /etc/apt/sources.list.d/nginx.list

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/mainline/ubuntu $(lsb_release -cs) nginx" |
    sudo tee /etc/apt/sources.list.d/nginx.list

echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" |
    sudo tee /etc/apt/preferences.d/99nginx

sudo apt update
sudo apt install nginx

# 修改配置文件
sudo sed -i "s|^user\s\+.*;$|user $SUDO_USER;|" /etc/nginx/nginx.conf

grep -n 'gzip' /etc/nginx/nginx.conf >/tmp/nginx_$$

if [ -s /tmp/nginx_$$ ]; then
    line_number=$(head -n 1 /tmp/nginx_$$ | cut -d: -f1)

    ARGS=()
    ARGS+=('proxy_set_header Host $host;')
    ARGS+=('proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;')
    ARGS+=('proxy_set_header X-Forwarded-Proto $scheme;')
    ARGS+=('proxy_set_header X-Forwarded-Host $host:$server_port;')
    ARGS+=('proxy_http_version 1.1;')

    add_string=$(printf '%s\\n' "${ARGS[@]}")
    sudo sed -i "${line_number}a\\$add_string" /etc/nginx/nginx.conf
    echo "${GREEN}修改 nginx.conf 完成${NC}"
else
    echo "${YELLOW}nginx.conf 文件中未找到 gzip${NC}"
fi

rm /tmp/nginx_$$

sudo \cp $bashpath/nginx/static.config /etc/nginx/conf.d

sudo systemctl start nginx
